package com.hcms.admin.security;

import cn.hutool.json.JSONUtil;
import com.hcms.admin.dto.SysAdminLoginResponse;
import com.hcms.common.api.CommonResponse;
import com.hcms.common.config.CmsJwtProperties;
import com.hcms.common.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AdminAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CmsJwtProperties jwtConfig;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.info("Run onAuthenticationSuccess()");
        Object principal = authentication.getPrincipal();
        CommonResponse<SysAdminLoginResponse> result;
        if (principal instanceof UserDetails) {
            //生成JWT
            logger.info("Generate JWT Token");
            UserDetails userDetails = (UserDetails) principal;
            String token = jwtTokenUtil.createToken(userDetails.getUsername());
            SysAdminLoginResponse loginResult = SysAdminLoginResponse.builder()
                    .tokenPrefix(jwtConfig.getTokenPrefix())
                    .token(token)
                    .build();
            result = new CommonResponse<>(HttpStatus.OK, "OK", loginResult);
        } else {
            logger.error("Principal is not a UserDetails subclass");
            result = new CommonResponse<>(HttpStatus.BAD_REQUEST, "登录失败");
        }
        logger.info("User login success");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setStatus(result.getStatus());
        response.getWriter().println(JSONUtil.toJsonStr(result));
        response.getWriter().flush();
    }

}
